package bank;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.af.plugins.sms.PropertiesReaderPlugin;
import com.aote.logic.LogicServer;

@Transactional
public class BankFileDeal {

	@Autowired
	private LogicServer logicServer;

	private String path;

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	private PropertiesReaderPlugin prop = new PropertiesReaderPlugin();

	public void getSource() {

		File files = new File(path);

		File[] file = files.listFiles();

		for (int i = 0; i < file.length; i++) {
			if (file[i].isFile()) {
				// 获取文件名，判断文件名是否符合格式
				if (isLegitimacy(file[i].getAbsolutePath())) {
					// 对文件内容进行解析返回jsonArray
					try {
						dealFile(file[i]);
						writeToNewPath(file[i], "bak");
					} catch (Exception e) {
						writeToNewPath(file[i], "error");
					}
				}

			}
		}
	}

	/**
	 * 判断文件名是否合法(以nx和yz开头为合法)
	 * 
	 * @param path
	 * @return
	 */
	private boolean isLegitimacy(String path) {
		String new_path = path.replace("\\", "/");
		String filename = new_path.split("/")[new_path.split("/").length - 1];
		return (filename.startsWith("nx") || filename.startsWith("yz"));

	}

	private void dealFile(File file) throws Exception {
		String str = null;
		BufferedReader bf = null;
		bf = new BufferedReader(new InputStreamReader(new FileInputStream(
				file), "GBK"));
		int i = 0;
		while ((str = bf.readLine()) != null) {
			Date trade_date = null;
			if (i == 0) {
				// 第一条为汇总信息 （需要获取日期值）
				trade_date = convertToDate(str.split("\\|")[0]);
				i++;
				continue;
			}
			JSONObject job = new JSONObject();
			String[] data = str.split("\\|");
			job.put("f_trade_date", trade_date);
			job.put("f_trade_number", data[0]);
			job.put("f_user_id", data[2]);
			job.put("f_trade_type", data[4]);
			job.put("f_total_charge", data[6]);
			job.put("f_terminal_id", data[7]);
			job.put("f_organizat_id", data[8]);
			job.put("f_bank_name",
					new JSONObject(prop.read("bank.properties", data[9]))
							.get("bankname")); // 需要从properties中拿
			job.put("f_comtypenum", data[10]);

			logicServer.run("bankFileDeal", job);

		}
		bf.close();
	}

	private void writeToNewPath(File file, String target) {

		// 获取新的路径
		String newpath = path + "\\" + target + "\\" + file.getName();
		BufferedReader read = null;
		FileWriter write = null;
		try {
			read = new BufferedReader(new InputStreamReader(
					new FileInputStream(file), "GBK"));
			write = new FileWriter(new File(newpath), true);

			String temp;
			while ((temp = read.readLine()) != null) {
				write.write(temp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				read.close();
				write.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public boolean deleteFile(File file) {
		if (file.exists() && file.isFile()) {
			return file.delete();
		}
		return true;
	}

	public static void main(String[] args) {
		BankFileDeal bank = new BankFileDeal();
		String str = "E:\\奥枫\\新产品\\签约\\readtest\\nx20171020.txt";
		File file = new File(str);
		System.out.println(bank.deleteFile(file));

	}

	private Date convertToDate(String str) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

		Date date = null;
		try {
			date = sdf.parse(str);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}
}
